<template>
	<view class="container">

		<!-- 内容输入区域 -->
		<view class="content-box">
			<!-- 文本输入区域 -->
			<u-textarea v-model="form.content" placeholder="分享学习心得..." height="400" count maxlength="1000" autoHeight
				:style="{ minHeight: '400rpx' }" border="none"></u-textarea>

			<!-- 图片上传区域 -->
			<view class="upload-area">
				<u-upload :fileList="images" @afterRead="afterRead" @delete="deletePic" name="1" multiple :maxCount="9"
					previewFullImage :deletable="true" :showProgress="false" :previewImage="true">
					<template v-slot:deleteIcon="{ index }">
						<view class="custom-delete" @click.stop="deletePic({ index })">
							<u-icon name="close" color="#fff" size="16"></u-icon>
						</view>
					</template>
				</u-upload>
			</view>

			<!-- 工具栏 - 三个按钮同行 -->
			<!-- 		<view class="toolbar">
				<view class="toolbar-button" @click="chooseLocation">
					<u-icon name="map" size="28"></u-icon>
					<text>位置</text>
				</view>
				<view class="toolbar-button" @click="showTagPopup = true">
					<u-icon name="tags" size="28"></u-icon>
					<text>标签</text>
				</view>
			</view> -->
		</view>

		<!-- 底部发布按钮 -->
		<view class="footer">
			<u-button type="primary" shape="circle" text="发布" :disabled="!(form.content)"
				@click="handleSubmit"></u-button>
		</view>

		<!-- 标签选择弹窗 -->
		<!-- 		<u-popup :show="showTagPopup" mode="bottom" @close="showTagPopup = false">
			<view class="tag-popup">
				<view class="popup-header">
					<text class="title">选择标签</text>
					<u-icon name="close" @click="showTagPopup = false"></u-icon>
				</view>
				<view class="tag-list">
					<u-tag v-for="tag in tags" :key="tag" :text="tag" plain size="large"
						:type="selectedTags.includes(tag) ? 'primary' : 'info'" @click="toggleTag(tag)"></u-tag>
				</view>
				<u-button type="primary" text="确定" @click="showTagPopup = false"></u-button>
			</view>
		</u-popup> -->
	</view>
</template>

<script>
	import storage from '@/utils/storage';
	import config from '@/config';
	import {
		addPost
	} from '@/api/bbs/post'
	export default {
		data() {
			return {
				form: {
					content: '',
				},
				images: [],
				showTagPopup: false,
				tags: ['学习', '心得', '经验', '技巧', '问题', '讨论'],
				selectedTags: [],
			};
		},
		onLoad() {
			// 正确获取 userId（假设存储在 Vuex 的 user 模块中）
			this.form.userId = this.$store.state.user.userId;

			// 如果 Vuex 中没有，尝试从本地存储获取
			if (!this.form.userId) {
				this.form.userId = storage.get('userId');
			}
			console.log('当前用户ID:', this.form.userId);
		},
		methods: {
			chooseImage() {
				const remaining = 9 - this.images.length;
				if (remaining <= 0) {
					uni.showToast({
						title: '最多上传9张图片',
						icon: 'none'
					});
					return;
				}
				uni.chooseImage({
					count: remaining,
					sizeType: ['original', 'compressed'],
					sourceType: ['album', 'camera'],
					success: (res) => {
						this.images = this.images.concat(
							res.tempFilePaths.map(path => ({
								url: path
							}))
						);
						console.log()
					}
				});
			},
			//  修改afterRead方法
			// async afterRead(event) {
			// 	uni.showLoading({
			// 		title: '上传中...',
			// 		mask: true
			// 	});
			// 	try {
			// 		const files = Array.isArray(event.file) ? event.file : [event.file];
			// 		const uploadTasks = files.map(file => this.uploadFile(file));
			// 		const results = await Promise.all(uploadTasks);
			// 		// this.images = this.images.concat(files)
			// 		results.forEach(res => {
			// 			if (res.code === 200) {
			// 				this.images.push({
			// 					url: res.fileName // 使用后端返回的文件名
			// 				});
			// 			}
			// 		});
			// 	} catch (err) {
			// 		uni.showToast({
			// 			title: `上传失败: ${err.message}`,
			// 			icon: 'none'
			// 		});
			// 	} finally {
			// 		uni.hideLoading();
			// 	}
			// },
			// // 新增上传文件方法
			// uploadFile(file) {
			// 	return new Promise((resolve, reject) => {
			// 		uni.uploadFile({
			// 			url: config.baseUrl + '/common/upload', // 使用若依统一上传接口
			// 			filePath: file.url,
			// 			name: 'file',
			// 			header: {
			// 				'Authorization': 'Bearer ' + this.$store.state.user.token // 添加认证token
			// 			},
			// 			formData: {
			// 				uploadType: 'post_image' // 按业务分类
			// 			},
			// 			success: (res) => {
			// 				const data = JSON.parse(res.data);
			// 				if (data.code === 200) {
			// 					resolve(data);
			// 				} else {
			// 					reject(new Error(data.msg || '上传失败'));
			// 				}
			// 			},
			// 			fail: (err) => reject(err)
			// 		});
			// 	});
			// },
			async afterRead(event) {
				// 获取新选择的文件（临时路径）
				const newFiles = Array.isArray(event.file) ? event.file : [event.file];

				// 只更新显示用的图片列表（不上传）
				this.images = this.images.concat(
					newFiles.map(file => ({
						url: file.url, // 临时路径用于预览
						isUploaded: false, // 标记未上传
						tempFile: file // 保留原始文件对象
					}))
				);
			},
			async uploadFile(file) {
				return new Promise((resolve, reject) => {
					uni.uploadFile({
						url: config.baseUrl + '/common/upload',
						filePath: file.url,
						name: 'file',
						header: {
							'Authorization': 'Bearer ' + this.$store.state.user.token
						},
						formData: {
							uploadType: 'post_image'
						},
						success: (res) => {
							const data = JSON.parse(res.data);
							if (data.code === 200) {
								resolve({
									...data,
									originalUrl: file.url // 保留原始URL用于匹配
								});
							} else {
								reject(new Error(data.msg || '上传失败'));
							}
						},
						fail: (err) => reject(err)
					});
				});
			},
			deletePic(event) {
				this.images.splice(event.index, 1);
			},
			chooseLocation() {
				uni.chooseLocation({
					success: (res) => {
						uni.showToast({
							title: `已选择: ${res.name}`,
							icon: 'none'
						});
					}
				});
			},
			toggleTag(tag) {
				const index = this.selectedTags.indexOf(tag);
				if (index > -1) {
					this.selectedTags.splice(index, 1);
				} else {
					if (this.selectedTags.length >= 3) {
						uni.showToast({
							title: '最多选择3个标签',
							icon: 'none'
						});
						return;
					}
					this.selectedTags.push(tag);
				}
			},
			// async handleSubmit() {
			// 	if (!this.form.content) {
			// 		uni.showToast({
			// 			title: '请填写内容',
			// 			icon: 'none'
			// 		});
			// 		return;
			// 	}

			// 	// 构造参数
			// 	const params = {
			// 		content: this.form.content,
			// 		userId: this.$store.state.user.userId, // 从Vuex获取
			// 		imageUrl: this.images.map(img => img.url) // 转换图片格式
			// 	};

			// 	uni.showLoading({
			// 		title: '发布中...'
			// 	});
			// 	try {
			// 		const res = await addPost(params);
			// 		if (res.code === 200) {

			// 			uni.showToast({
			// 				title: '发布成功',
			// 				icon: 'success',
			// 				success: () => {
			// 					// 保留当前页面的用户ID等状态
			// 					uni.redirectTo({
			// 						url: '/pages/circle/post/index?keepState=1' // 通过参数保持状态
			// 					});
			// 				}
			// 			});
			// 			setTimeout(() => uni.navigateBack(), 1500);
			// 		}
			// 	} catch (err) {
			// 		uni.showToast({
			// 			title: '发布失败',
			// 			icon: 'none'
			// 		});
			// 	} finally {
			// 		uni.hideLoading();
			// 	}
			// },
			async handleSubmit() {
				if (!this.form.content) {
					uni.showToast({
						title: '请填写内容',
						icon: 'none'
					});
					return;
				}

				uni.showLoading({
					title: '发布中...',
					mask: true
				});

				try {
					// 1. 先上传所有未上传的图片
					const unuploaded = this.images.filter(img => !img.isUploaded);
					const uploadTasks = unuploaded.map(img => this.uploadFile(img.tempFile));
					const results = await Promise.all(uploadTasks);

					// 2. 更新图片状态
					results.forEach(res => {
						const index = this.images.findIndex(img => img.url === res.originalUrl);
						if (index !== -1) {
							this.images[index] = {
								url: res.fileName, // 替换为服务器返回的路径
								isUploaded: true
							};
						}
					});

					// 3. 提交帖子数据
					const res = await addPost({
						content: this.form.content,
						userId: this.$store.state.user.userId,
						imageUrl: this.images.map(img => img.url) // 使用最终URL
					});

					if (res.code === 200) {
						uni.showToast({
							title: '发布成功',
							icon: 'success'
						});
						// 获取当前页面栈
						const pages = getCurrentPages();
						// 获取上一页实例
						const prevPage = pages[pages.length - 2];

						// 调用上一页的刷新方法
						if (prevPage && prevPage.$vm.getPostList) {
							prevPage.$vm.pageNum = 1;
							prevPage.$vm.getPostList();
						}
						setTimeout(() => uni.navigateBack(), 1500);
					}
				} catch (err) {
					uni.showToast({
						title: `发布失败: ${err.message}`,
						icon: 'none'
					});
				} finally {
					uni.hideLoading();
				}
			},
			async addPostList() {
				try {
					// 构造请求参数
					const params = {
						content: this.form.content,
						userId: this.form.userId,
						images: this.images.map(img => img.url).join(','), // 图片URL拼接为字符串
						// 	tags: this.selectedTags.join(',') // 标签拼接为字符串
					};

					const res = await addPost(params);

					if (res.code === 200) {
						uni.hideLoading();
						uni.showToast({
							title: '发布成功',
							icon: 'success'
						});
						setTimeout(() => uni.navigateBack(), 1500);
					} else {
						throw new Error(res.msg || '发布失败');
					}
				} catch (err) {
					uni.hideLoading();
					uni.showToast({
						title: err.message,
						icon: 'none'
					});
					console.error('发布失败:', err);
				}
			}
		}
	};
</script>

<style scoped>
	.container {
		height: 100vh;
		display: flex;
		flex-direction: column;
		background-color: #fff;
	}

	.content-box {
		flex: 1;
		padding: 20rpx;
		/* overflow-y: auto; */
	}

	.u-textarea {
		min-height: 400rpx !important;
		font-size: 16px;
		line-height: 1.6;
		padding: 20rpx;
		background-color: #fff;
		border-radius: 12rpx;
	}

	.upload-area {

		margin-top: 30rpx;
		padding: 20rpx;
		background-color: #fff;
		border-radius: 12rpx;
	}

	/* 工具栏样式 - 三个按钮同行 */
	.toolbar {
		display: flex;
		justify-content: space-around;
		padding: 20rpx;
		background-color: #fff;
		border-radius: 12rpx;
		margin-top: 20rpx;
	}

	.toolbar-button {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 0 20rpx;
	}

	.toolbar-button text {
		font-size: 12px;
		color: #666;
		margin-top: 5rpx;
	}

	.custom-delete {
		position: absolute;
		top: 8rpx;
		right: 8rpx;
		width: 36rpx;
		height: 36rpx;
		background-color: rgba(0, 0, 0, 0.5);
		border-radius: 50%;
		display: flex;
		justify-content: center;
		align-items: center;
		z-index: 10;
	}

	.footer {
		position: fixed;
		left: 0;
		right: 0;
		bottom: 0;
		padding: 20rpx;
		/* 		border-top: 1rpx solid #eee; */
	}

	.tag-popup {
		padding: 30rpx;
	}

	.popup-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 30rpx;
	}

	.popup-header .title {
		font-size: 18px;
		font-weight: bold;
	}

	.tag-list {
		display: flex;
		flex-wrap: wrap;
		margin-bottom: 30rpx;
	}

	.tag-list>* {
		margin-right: 20rpx;
		margin-bottom: 20rpx;
	}
</style>